import {
  useCallback,
  useEffect,
  useState,
  createContext,
  useContext,
} from 'react';

/**
 * 主题类型定义
 */
export type ThemeMode = 'light' | 'dark' | 'auto' | 'custom';

/**
 * 主题颜色配置
 */
export interface ThemeColors {
  // 背景色
  background: string;
  surface: string;
  overlay: string;

  // 文字色
  text: string;
  textSecondary: string;
  textMuted: string;

  // 边框和分割线
  border: string;
  divider: string;

  // 交互色
  primary: string;
  primaryHover: string;
  secondary: string;

  // 状态色
  success: string;
  warning: string;
  error: string;
  info: string;

  // 阴影
  shadow: string;
  shadowLight: string;
  shadowDark: string;
}

/**
 * 完整主题配置
 */
export interface Theme {
  mode: ThemeMode;
  colors: ThemeColors;
  spacing: {
    xs: string;
    sm: string;
    md: string;
    lg: string;
    xl: string;
  };
  borderRadius: {
    sm: string;
    md: string;
    lg: string;
    xl: string;
  };
  typography: {
    fontFamily: string;
    fontSize: {
      xs: string;
      sm: string;
      md: string;
      lg: string;
      xl: string;
    };
    fontWeight: {
      normal: string;
      medium: string;
      semibold: string;
      bold: string;
    };
  };
  animation: {
    duration: {
      fast: string;
      normal: string;
      slow: string;
    };
    easing: {
      ease: string;
      easeIn: string;
      easeOut: string;
      easeInOut: string;
    };
  };
}

/**
 * 预定义主题
 */
export const LIGHT_THEME: Theme = {
  mode: 'light',
  colors: {
    background: '#ffffff',
    surface: '#f8fafc',
    overlay: 'rgba(0, 0, 0, 0.5)',

    text: '#1a202c',
    textSecondary: '#4a5568',
    textMuted: '#718096',

    border: '#e2e8f0',
    divider: '#f1f5f9',

    primary: '#3b82f6',
    primaryHover: '#2563eb',
    secondary: '#64748b',

    success: '#10b981',
    warning: '#f59e0b',
    error: '#ef4444',
    info: '#3b82f6',

    shadow: 'rgba(0, 0, 0, 0.1)',
    shadowLight: 'rgba(0, 0, 0, 0.05)',
    shadowDark: 'rgba(0, 0, 0, 0.2)',
  },
  spacing: {
    xs: '4px',
    sm: '8px',
    md: '16px',
    lg: '24px',
    xl: '32px',
  },
  borderRadius: {
    sm: '4px',
    md: '8px',
    lg: '12px',
    xl: '16px',
  },
  typography: {
    fontFamily:
      '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
    fontSize: {
      xs: '12px',
      sm: '14px',
      md: '16px',
      lg: '18px',
      xl: '20px',
    },
    fontWeight: {
      normal: '400',
      medium: '500',
      semibold: '600',
      bold: '700',
    },
  },
  animation: {
    duration: {
      fast: '150ms',
      normal: '300ms',
      slow: '500ms',
    },
    easing: {
      ease: 'cubic-bezier(0.4, 0, 0.2, 1)',
      easeIn: 'cubic-bezier(0.4, 0, 1, 1)',
      easeOut: 'cubic-bezier(0, 0, 0.2, 1)',
      easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',
    },
  },
};

export const DARK_THEME: Theme = {
  ...LIGHT_THEME,
  mode: 'dark',
  colors: {
    background: '#0f172a',
    surface: '#1e293b',
    overlay: 'rgba(0, 0, 0, 0.7)',

    text: '#f1f5f9',
    textSecondary: '#cbd5e1',
    textMuted: '#94a3b8',

    border: '#334155',
    divider: '#1e293b',

    primary: '#60a5fa',
    primaryHover: '#3b82f6',
    secondary: '#94a3b8',

    success: '#34d399',
    warning: '#fbbf24',
    error: '#f87171',
    info: '#60a5fa',

    shadow: 'rgba(0, 0, 0, 0.3)',
    shadowLight: 'rgba(0, 0, 0, 0.2)',
    shadowDark: 'rgba(0, 0, 0, 0.5)',
  },
};

/**
 * 主题上下文
 */
interface ThemeContextValue {
  theme: Theme;
  setTheme: (theme: Partial<Theme>) => void;
  setThemeMode: (mode: ThemeMode) => void;
  toggleTheme: () => void;
  applyTheme: () => void;
}

const ThemeContext = createContext<ThemeContextValue | null>(null);

/**
 * 主题系统 Hook
 *
 * 🎯 设计理念：
 * 1. CSS 变量驱动：所有主题通过 CSS 自定义属性实现
 * 2. 多模式支持：浅色、深色、跟随系统、完全自定义
 * 3. 状态持久化：本地存储用户偏好，页面刷新后保持
 * 4. 实时切换：主题变化立即生效，无需重新渲染
 *
 * 🎨 主题模式：
 * - light: 浅色主题 (白色背景，深色文字)
 * - dark: 深色主题 (深色背景，浅色文字)
 * - auto: 跟随系统 (prefers-color-scheme)
 * - custom: 完全自定义主题配置
 *
 * 🏗️ 架构设计：
 * - ThemeProvider: Context 提供者，管理全局主题状态
 * - useTheme: Hook 消费主题状态和方法
 * - ThemeToggle: 主题切换组件
 * - CSS 变量: 运行时动态应用主题
 *
 * 🎯 设计令牌系统：
 * - 颜色：primary, secondary, success, warning, error
 * - 间距：xs, sm, md, lg, xl (4px, 8px, 16px, 24px, 32px)
 * - 圆角：sm, md, lg (4px, 8px, 12px)
 * - 字体：size, weight, family
 * - 动画：duration, easing
 *
 * 💾 持久化策略：
 * - localStorage 存储用户偏好
 * - 页面刷新后自动恢复
 * - 系统主题变化自动响应
 *
 * 🌐 兼容性考虑：
 * - CSS 变量 fallback 值
 * - 媒体查询支持检测
 * - 渐进增强，不影响基础功能
 */
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

/**
 * 主题提供者属性
 */
interface ThemeProviderProps {
  children: React.ReactNode;
  defaultTheme?: Theme;
  storageKey?: string;
  enableSystemTheme?: boolean;
}

/**
 * 主题提供者组件
 */
export const ThemeProvider: React.FC<ThemeProviderProps> = ({
  children,
  defaultTheme = LIGHT_THEME,
  storageKey = 'modal-sheet-theme',
  enableSystemTheme = true,
}) => {
  const [theme, setThemeState] = useState<Theme>(defaultTheme);

  // 检测系统主题
  const getSystemTheme = useCallback((): ThemeMode => {
    if (typeof window === 'undefined') return 'light';
    return window.matchMedia('(prefers-color-scheme: dark)').matches
      ? 'dark'
      : 'light';
  }, []);

  // 从本地存储加载主题
  const loadThemeFromStorage = useCallback((): Theme => {
    if (typeof window === 'undefined') return defaultTheme;

    try {
      const stored = localStorage.getItem(storageKey);
      if (stored) {
        const parsedTheme = JSON.parse(stored);
        return { ...defaultTheme, ...parsedTheme };
      }
    } catch (error) {
      console.warn('Failed to load theme from storage:', error);
    }

    return defaultTheme;
  }, [defaultTheme, storageKey]);

  // 保存主题到本地存储
  const saveThemeToStorage = useCallback(
    (themeToSave: Theme) => {
      if (typeof window === 'undefined') return;

      try {
        localStorage.setItem(storageKey, JSON.stringify(themeToSave));
      } catch (error) {
        console.warn('Failed to save theme to storage:', error);
      }
    },
    [storageKey]
  );

  // 应用主题到 CSS 变量
  const applyTheme = useCallback(() => {
    if (typeof window === 'undefined') return;

    const root = document.documentElement;
    const { colors, spacing, borderRadius, typography, animation } = theme;

    // 应用颜色变量
    Object.entries(colors).forEach(([key, value]) => {
      root.style.setProperty(`--modal-color-${key}`, value);
    });

    // 应用间距变量
    Object.entries(spacing).forEach(([key, value]) => {
      root.style.setProperty(`--modal-spacing-${key}`, value);
    });

    // 应用圆角变量
    Object.entries(borderRadius).forEach(([key, value]) => {
      root.style.setProperty(`--modal-radius-${key}`, value);
    });

    // 应用字体变量
    root.style.setProperty('--modal-font-family', typography.fontFamily);
    Object.entries(typography.fontSize).forEach(([key, value]) => {
      root.style.setProperty(`--modal-font-size-${key}`, value);
    });
    Object.entries(typography.fontWeight).forEach(([key, value]) => {
      root.style.setProperty(`--modal-font-weight-${key}`, value);
    });

    // 应用动画变量
    Object.entries(animation.duration).forEach(([key, value]) => {
      root.style.setProperty(`--modal-duration-${key}`, value);
    });
    Object.entries(animation.easing).forEach(([key, value]) => {
      root.style.setProperty(`--modal-easing-${key}`, value);
    });

    // 设置主题模式
    root.setAttribute('data-theme', theme.mode);
  }, [theme]);

  // 设置主题
  const setTheme = useCallback(
    (newTheme: Partial<Theme>) => {
      const updatedTheme = { ...theme, ...newTheme };
      setThemeState(updatedTheme);
      saveThemeToStorage(updatedTheme);
    },
    [theme, saveThemeToStorage]
  );

  // 设置主题模式
  const setThemeMode = useCallback(
    (mode: ThemeMode) => {
      let newTheme: Theme;

      switch (mode) {
        case 'dark':
          newTheme = { ...DARK_THEME };
          break;
        case 'light':
          newTheme = { ...LIGHT_THEME };
          break;
        case 'auto': {
          const systemMode = getSystemTheme();
          newTheme =
            systemMode === 'dark' ? { ...DARK_THEME } : { ...LIGHT_THEME };
          newTheme.mode = 'auto';
          break;
        }
        case 'custom':
          newTheme = { ...theme, mode: 'custom' };
          break;
        default:
          newTheme = { ...LIGHT_THEME };
      }

      setThemeState(newTheme);
      saveThemeToStorage(newTheme);
    },
    [theme, getSystemTheme, saveThemeToStorage]
  );

  // 切换主题
  const toggleTheme = useCallback(() => {
    const newMode = theme.mode === 'light' ? 'dark' : 'light';
    setThemeMode(newMode);
  }, [theme.mode, setThemeMode]);

  // 监听系统主题变化
  useEffect(() => {
    if (!enableSystemTheme || theme.mode !== 'auto') return;

    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    const handleChange = () => {
      if (theme.mode === 'auto') {
        const systemMode = getSystemTheme();
        const newTheme =
          systemMode === 'dark' ? { ...DARK_THEME } : { ...LIGHT_THEME };
        newTheme.mode = 'auto';
        setThemeState(newTheme);
      }
    };

    mediaQuery.addEventListener('change', handleChange);
    return () => mediaQuery.removeEventListener('change', handleChange);
  }, [theme.mode, enableSystemTheme, getSystemTheme]);

  // 初始化主题
  useEffect(() => {
    const savedTheme = loadThemeFromStorage();
    setThemeState(savedTheme);
  }, [loadThemeFromStorage]);

  // 应用主题到 DOM
  useEffect(() => {
    applyTheme();
  }, [applyTheme]);

  const contextValue: ThemeContextValue = {
    theme,
    setTheme,
    setThemeMode,
    toggleTheme,
    applyTheme,
  };

  return (
    <ThemeContext.Provider value={contextValue}>
      {children}
    </ThemeContext.Provider>
  );
};

/**
 * 主题切换器组件
 */
interface ThemeToggleProps {
  className?: string;
  showLabel?: boolean;
}

export const ThemeToggle: React.FC<ThemeToggleProps> = ({
  className = '',
  showLabel = true,
}) => {
  const { theme, setThemeMode } = useTheme();

  return (
    <div className={`theme-toggle ${className}`}>
      {showLabel && <span>主题:</span>}
      <select
        value={theme.mode}
        onChange={e => setThemeMode(e.target.value as ThemeMode)}
        className='theme-select'
      >
        <option value='light'>浅色</option>
        <option value='dark'>深色</option>
        <option value='auto'>跟随系统</option>
        <option value='custom'>自定义</option>
      </select>
    </div>
  );
};
